#drafted by Jeremy VanDerWal ( jjvanderwal@gmail.com ... www.jjvanderwal.com )
#GNU General Public License .. feel free to use / distribute ... no warranties

################################################################################
#define directories
work.dir='           '
mxe.dir = '/home/jc165798/Climate/CIAS/Australia/1km/bioclim_mxe/'
maxent.jar = "/home/jc149336/Maxent/maxent.jar"
climate.dir = '/home/jc165798/Climate/CIAS/Australia/1km/baseline.76to05/bioclim/'
################################################################################
#list the projections, cycle thorugh them and project the models onto them
proj.list = list.files(mxe.dir) #list the projections
proj.list = proj.list[intersect(grep('RCP',proj.list),c(grep('2035',proj.list),grep('2055',proj.list),grep('2085',proj.list)))] #subset it to simply current and 2080 data

species = list.files(work.dir) #get a list of species

#cycle through each of the species
for (spp in species) { #spp=species[1]
	spp.dir = paste(work.dir,spp,'/',sep=''); setwd(spp.dir) #set the working directory to the species directory

	zz = file(paste('02.',spp,'project.models.sh',sep=''),'w') ##create the sh file
		cat('#!/bin/bash\n',file=zz)
		cat('cd ',spp.dir,'\n',sep='',file=zz)
		cat('source /etc/profile.d/modules.sh\n',file=zz)
		cat('module load java\n',file=zz)
		dir.create('output/ascii_WTcurrent/',recursive=TRUE) #create the output directory for all maps
		#cycle through the projections
		for (tproj in proj.list) cat('java -mx1024m -cp ',maxent.jar,' density.Project ',spp.dir,'output/',spp,'.lambdas ',mxe.dir,tproj,' ',spp.dir,'output/ascii_WTcurrent/',tproj,'.asc fadebyclamping nowriteclampgrid\n',sep="",file=zz)
		cat('java -mx2048m -cp ',work.dir,'maxent.jar density.Project ',spp.dir,'output/',spp,'.lambdas ',climate.dir,' ',spp.dir,'output/ascii/1990.asc fadebyclamping nowriteclampgrid\n',sep="",file=zz)
		cat('gzip ',spp.dir,'output/ascii_WTcurrent/*asc\n',sep='',file=zz)#Try not to zip
	close(zz)

	#submit the script
	system(paste('qsub -m n 02.',spp,'project.models.sh',sep=''))
	}
